package com.lin.manager.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lin.manager.common.ex.BizException;
import com.lin.manager.common.resp.DataPage;
import com.lin.manager.system.dao.SysDicDao;
import com.lin.manager.system.entity.SysDicEntity;
import com.lin.manager.system.model.vo.DictQueryParamVo;
import com.lin.manager.system.service.SysDicService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @作者: 林江
 * @创建时间: 2024-03-13 14:37:36
 * @功能:
 */
@Service
public class SysDicServiceImpl implements SysDicService {
    @Autowired
    SysDicDao sysDicDao;

    @Override
    public DataPage<SysDicEntity> listPage(DictQueryParamVo vo) {
        LambdaQueryWrapper<SysDicEntity> wrapper = new QueryWrapper<SysDicEntity>().lambda()
                .orderByDesc(SysDicEntity::getCreateTime)
                .like(StringUtils.isNotBlank(vo.getKey()), SysDicEntity::getName, vo.getKey());

        Page<SysDicEntity> selectPage = sysDicDao.selectPage(new Page<>(vo.getPageNum(), vo.getPageSize()), wrapper);
        return DataPage.<SysDicEntity>builder()
                .page(selectPage).build();
    }

    @Override
    public void add(SysDicEntity sysDic) {
        checkCode(sysDic.getId(), sysDic.getCode());
        sysDicDao.insert(sysDic);
    }

    @Override
    public void update(SysDicEntity sysDic) {
        checkCode(sysDic.getId(), sysDic.getCode());
        sysDicDao.updateById(sysDic);
    }

    @Override
    public void del(String id) {
        sysDicDao.deleteById(id);
    }

    /**
     * 角色编码必须唯一
     *
     * @param id
     * @param code
     */
    private void checkCode(Long id, String code) {
        LambdaQueryWrapper<SysDicEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDicEntity::getCode, code);
        if (id != null) {
            wrapper.ne(SysDicEntity::getId, id);
        }
        Long count = sysDicDao.selectCount(wrapper);
        if (count > 0) {
            throw new BizException("字典编码重复，请重新设置");
        }
    }
}
